<template>
<a-spin :spinning="confirmLoading">
    <j-form-container disabled>
    <!-- 主表单区域 -->
    <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
        <a-col :span="12">
            <a-form-model-item label="原料入库单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
            <a-input v-model="model.code" placeholder="" disabled></a-input>
            </a-form-model-item>
        </a-col>
        <a-col :span="12">
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flowType">
            <j-dict-select-tag
                type="list"
                v-model="model.flowType"
                dictCode="material_store_flow_type"
                placeholder=""
                :disabled="formDisabled"
            />
            </a-form-model-item>
        </a-col>
        </a-row>
        <a-row>
        <a-col :span="12">
            <a-form-model-item
            label="供货单位"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="supplierCompany"
            >
            <a-input v-model="model.supplierCompany" placeholder="" :disabled="true"></a-input>
            </a-form-model-item>
        </a-col>
        <a-col :span="12">
            <a-form-model-item
            label="进厂日期"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="enterPlantDate"
            >
            <j-date
                placeholder=""
                v-model="model.enterPlantDate"
                style="width: 100%"
                :disabled="formDisabled"
            />
            </a-form-model-item>
        </a-col>
        </a-row>
        <a-row>
        <a-col :span="12">
            <a-form-model-item label="宝洁供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pgSupplierName">
            <j-popup
                v-model="model.pgSupplierName"
                field="pgSupplierName"
                org-fields="supplier_name,supplier_code,id"
                dest-fields="pgSupplierName,pgSupplierCode,pgSupplierId"
                code="purchase_supplier_info"
                :multi="false"
                @input="popupCallback"
                placeholder=""
            />
            </a-form-model-item>
        </a-col>
        <a-col :span="12">
            <a-form-model-item label="宝洁供应商编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pgSupplierCode">
            <a-input v-model="model.pgSupplierCode" placeholder="" :disabled="true"></a-input>
            </a-form-model-item>
        </a-col>
        <a-input v-model="model.pgSupplierId" type="hidden"></a-input>
        </a-row>
        <a-row>
        <a-col :span="12">
            <a-form-model-item
            label="保洁采购订单号"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="pgPurchaseOrderNo"
            >
            <a-input v-model="model.pgPurchaseOrderNo" placeholder=""></a-input>
            </a-form-model-item>
        </a-col>
        </a-row>
        <a-row>
        <a-col :span="12">
            <a-form-model-item
            label="当前车牌号："
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="plateNumber"
            >
            <plate-number-input
                v-model="model.plateNumber"
            />
            </a-form-model-item>
        </a-col>
        <a-col :span="12">
            <a-form-model-item
            label="司机名称"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="driverName"
            >
            <a-input v-model="model.driverName"></a-input>
            </a-form-model-item>
        </a-col>
        </a-row>
        <a-row>
        <a-col :span="12">
            <a-form-model-item
            label="联系方式"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="driverPhone"
            :rules="rules.driverPhone"
            >
            <a-input v-model="model.driverPhone"></a-input>
            </a-form-model-item>
        </a-col>
        <a-col :span="12" >
            <a-form-model-item label="进厂目的" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purpose">
            <j-dict-select-tag
                type="list"
                v-model="model.purpose"
                dictCode="driver_purpose"
            />
            </a-form-model-item>
        </a-col>
        </a-row>
        <a-row style="margin-left: -16.6%;margin-top: 5px">
        <a-col :span="24">
            <a-form-model-item
            label="备注"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="remark"
            >
            <a-textarea
                :disabled="formDisabled"
                v-model="model.remark"
                :rows="5"
                allow-clear
                showCount
                placeholder=""
            ></a-textarea>
            </a-form-model-item>
        </a-col>
        </a-row>
        <a-input v-model="model.sourceFrom" type="hidden" />
        <a-input v-model="model.procurementOrderId" type="hidden" />
        <a-input v-model="model.warehouseCode" type="hidden" />
    </a-form-model>
    </j-form-container>
    <a-row style="margin-top: 10px">
    </a-row>
    <a-row>
    <a-col :span="24">
        <j-vxe-table
        keep-source
        :ref="refKeys[1]"
        :loading="fileTable.loading"
        :columns="fileTable.columns"
        :dataSource="fileTable.dataSource"
        :maxHeight="300"
        disabled
        :rowNumber="true"
        :rowSelection="false"
        :toolbar="false"
        >
        <template v-slot:action="{row}">
            <a @click="handlePreviewFile(row)">预览</a>
        </template>
        </j-vxe-table>
    </a-col>
    </a-row>
    <a-row style="margin-top: 20px">
    </a-row>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
    <a-tab-pane tab="原料入库通知单明细" :key="refKeys[0]" :forceRender="true">
        <a-row>
        <a-col :span="24">
            <j-vxe-table
            keep-source
            :ref="refKeys[0]"
            :loading="bussMaterialProcurementDetailTable.loading"
            :columns="bussMaterialProcurementDetailTable.columns"
            :dataSource="bussMaterialProcurementDetailTable.dataSource"
            :maxHeight="300"
            disabled
            :rowNumber="false"
            :rowSelection="false"
            class="j-table-force-nowrap1"
            :clickSelectRow="true"
            rowSelectionType="radio"
            @edit-closed="editClosedEvent"
            >
            </j-vxe-table>
        </a-col>
        </a-row>
    </a-tab-pane>
    </a-tabs>
</a-spin>
</template>

<script>
import { getAction, httpAction, postAction } from '@/api/manage'
import { getRefPromise, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import moment from 'dayjs'
import ErpGoodsSupplier from '@/components/base/ErpGoodsSupplier'
import GoodsSupplier from '@/components/base/GoodsSupplier'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import TslSupplier from '@comp/tsl/TslSupplier.vue'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'
import TslSelectUserSingle from '@/components/tsl/TslSelectUserSingle.vue'
import { FilePreview } from '@/utils/tslCommon'
import Decimal from 'decimal.js'
import PlateNumberInput from '../../../srm/materialstore/modules/PlateNumberInput.vue'

export default {
    name: 'InboundStoreForm',
    mixins: [JVxeTableModelMixin],
    components: {
    JSelectDepart,
    ErpGoodsSupplier,
    GoodsSupplier,
    TslSupplier,
    TslSelectUserSingle,
    PlateNumberInput,
    },
    data() {
    return {
        rules: {
        },
        labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
        },
        wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
        },
        dict: {
        unit: [{ label: '个', value: '1' }],
        },
        priceTypeOption: [
        {
            value: '到库价格',
            label: '到库价格',
        },
        {
            value: '出厂价格',
            label: '出厂价格',
        },
        {
            value: '到港价格',
            label: '到港价格',
        },
        ],
        model: {
        sourceFrom: '1',
        code: '',
        flowType: '1',
        supplierCompany: '',
        remark: '',
        procurementOrderDetailId: '',
        procurementOrderId: '',
        procurementOrderCode: '',
        procurementPlanCode: '',
        applicationCode: '',
        warehouseCode: '',
        plateNumber: '', 
        province: '', 
        plateBody: '', 
        bussMaterialStoreNoticeDetailList: [],
        bussStoreNoticeFilesList: [],
        },
        supplier: {},
        supplyShow: true,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
        },
        refKeys: ['bussMaterialProcurementDetail','fileTable'],
        tableKeys: ['bussMaterialProcurementDetail'],
        activeKey: 'bussMaterialProcurementDetail',
        // 原料入库通知单明细
        bussMaterialProcurementDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
            {
            title: '序号',
            key: 'seq',
            type: JVXETypes.normal,
            width: '50px',
            },
            {
            title: '原料采购订单号',
            key: 'procurementOrderCode',
            type: JVXETypes.normal,
            width: '150px',
            },
            {
            title: '原料计划单号',
            key: 'procurementPlanCode',
            type: JVXETypes.normal,
            width: '150px',
            },
            {
            title: '原料请购单号',
            key: 'applicationCode',
            type: JVXETypes.normal,
            width: '150px',
            },
            {
            title: '物料编码',
            key: 'materialCode',
            type: JVXETypes.normal,
            width: '120px',
            },
            {
            title: '物料名称',
            key: 'materialName',
            type: JVXETypes.normal,
            width: '120px',
            },
            {
            title: '规格型号',
            key: 'spec',
            type: JVXETypes.normal,
            width: '120px',
            },
            {
            title: '单位',
            key: 'unit',
            type: JVXETypes.normal,
            width: '50px',
            },
            {
            title: '采购订单数量',
            key: 'procurementOrderNum',
            type: JVXETypes.normal,
            width: '120px',
            },
            {
            title: '已转入库单数量',
            key: 'transferredStoreNum',
            type: JVXETypes.normal,
            width: '120px',
            },
            {
            title: '未转入库单数量',
            key: 'notTransferredStoreNum',
            type: JVXETypes.normal,
            width: '120px',
            },
            {
            title: '已到数量',
            key: 'arrivedNum',
            type: JVXETypes.normal,
            width: '120px',
            },
            {
            title: '不合格数量',
            key: 'unqualifiedNum',
            type: JVXETypes.normal,
            width: '120px',
            },
            {
            title: '实收数量',
            key: 'actualAcceptNum',
            type: JVXETypes.normal,
            width: '120px',
            },
            {
            title: '本次转入库单数量',
            key: 'curTransferredStoreNum',
            type: JVXETypes.inputNumber,
            width: '120px',
            },
        ],
        },
        fileTable: {
        loading: false,
        dataSource: [],
        columns: [
            {
            title: '附件',
            key: 'filePath',
            type: JVXETypes.file,
            token: true,
            disabled:this.formDisabled,
            responseName: 'message',
            width: '200px',
            placeholder: '请选择文件',
            defaultValue: '',
            },
            {
            title: '附件说明',
            key: 'fileDesc',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            },
            {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
            },
        ],
        },
        url: {
        add: '/bussmaterialstorenotice/bussMaterialStoreNotice/add',
        edit: '/bussmaterialstorenotice/bussMaterialStoreNotice/edit',
        queryById: '/bussmaterialstorenotice/bussMaterialStoreNotice/queryById',
        bussMaterialProcurementDetail: {
            list: '/bussmaterialstorenotice/bussMaterialStoreNotice/queryBussMaterialStoreNoticeDetailByMainId',
        },
        bussMaterialStore: {
            list: '/bussmaterialstorenotice/bussMaterialStoreNotice/list',
            packageList: '/packagestorenotice/packageStoreNotice/list',
        }
        },
    }
    },
    props: {
    //表单禁用
    disabled: {
        type: Boolean,
        default: false,
        required: false,
    },
    customFormData: {
        type: Object,
        default: () => {
        return {}
        },
        required: false,
    },
    },
    computed: {
    formDisabled() {
        return this.disabled
    },
    },
    created() {
    },
    mounted() {},
    methods: {
    getPfCode() {
        postAction('/sys/fillRule/executeRuleByCode/procurement_store_code', {}).then((res) => {
        this.model.code = res.result
        })
    },
    loadVendor() {
        if (this.model.bussMaterialStoreNoticeDetailList && this.model.bussMaterialStoreNoticeDetailList.length > 0 && this.model.bussMaterialStoreNoticeDetailList[0].supplierId) {
        // 加载供应商信息
        getAction('/base/erpSupplier/queryById', { id: this.model.bussMaterialStoreNoticeDetailList[0].supplierId }).then((res) => {
            this.supplier = res.result
            this.model.supplierId = this.supplier.id
        })
        }
    },
    showDetails(id) {
        getAction('/bussmaterialstorenotice/bussMaterialStoreNotice/getDetailInfos', { procurementOrderId: id }).then((res) => {
        let data = res.result
        data.forEach((row, index) => {
            this.bussMaterialProcurementDetailTable.dataSource.push({
            procurementOrderCode: row.procurementOrderCode,
            procurementPlanCode: row.procurementPlanCode,
            applicationCode: row.applicationCode,
            procurementOrderDetailId: row.procurementOrderDetailId,
            procurementOrderId: row.procurementOrderId,
            materialId: row.materialId,
            materialCode: row.materialCode,
            materialName: row.materialName,
            spec: row.spec,
            unit: row.unit,
            procurementOrderNum: row.procurementOrderNum,
            seq: index + 1,
            })
        })
        })
    },
    editClosedEvent({ row, column, cellValue }) {
        // 当修改"本次订单数量"或"价格"时触发计算
        if (['curTransferredNum', 'price'].includes(column.property)) {
        // 确保值为数字类型
        const qty = parseFloat(row.curTransferredNum) || 0
        const price = parseFloat(row.price) || 0
        // 计算总价（保留两位小数）
        row.totalPrice = (qty * price).toFixed(2)
        }
    },
    getAllTable() {
        let values = this.tableKeys.map((key) => getRefPromise(this, key))
        return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter(record) {
        if(!record.entryType || !record.documentNumber){
            return
        }
        //如果没有明细先要复制一个空数组
        if (!record || record.bussMaterialStoreNoticeDetailList == null) {
        this.model.bussMaterialStoreNoticeDetailList = []
        }
        //根据不同的单据类型，查询不同的采购入库表
        let url = this.url.bussMaterialStore.list;
        switch (record.entryType) {
            //1.原料采购
            //2/五金采购
            //4.促销品采购
            //13.设备采购
            //14.备品备件采购
            //15.OEM采购
            //16通用采购
            case 1:
            case 2:
            case 3:
            case 13:
            case 14:
            case 15:
            case 16:
            url = this.url.bussMaterialStore.list
            break
            //3.包材采购
            case 'needEdit':
            url = this.url.bussMaterialStore.packageList
            break
            default:
            break
        }
        let storeParams = {
            sourceFrom: record.entryType,
            procurementOrderCode: record.documentNumber,
            status: 999,
        }
        getAction(url, storeParams).then(res => {
            if (res.success) {
                if(res.result && res.result.records?.length == 1){
                    this.model = res.result.records[0];
                    let params = { id: res.result.records[0].id }
                    this.requestSubTableData(
                        this.url.bussMaterialProcurementDetail.list,
                        params,
                        this.bussMaterialProcurementDetailTable,
                        this.fileTable
                    )
                    //刷新明细的时候 还要将这个数据传输到要提交的表单中
                    if (this.bussMaterialProcurementDetailTable) {
                        this.model.bussMaterialStoreNoticeDetailList = this.bussMaterialProcurementDetailTable.dataSource
                    }
                    if (this.fileTable) {
                        this.model.bussStoreNoticeFilesList = this.fileTable.dataSource
                    }
                }
            }
        })
        this.$nextTick(() => {})
    },
    requestSubTableData(url, params, table, fileTable) {
        getAction(url, params).then(res => {
        if (res.success) {
            table.dataSource = res.result.bussMaterialStoreNoticeDetailList.map(item => ({
            ...item,
            }))
            fileTable.dataSource = res.result.bussStoreNoticeFilesList
        }
        })
    },
    successBack(res) {
        let { result } = res
        this.model = result
        if (this.model.bussMaterialStoreNoticeDetailList && this.model.bussMaterialStoreNoticeDetailList.length > 0) {
        this.loadVendor()
        }
    },
    popupCallback(value,row){
        this.model = Object.assign(this.model, row);
    },
    handlePreviewFile(row) {
        let filePath = row.filePath
        FilePreview(filePath);
    },
    },
}
</script>

<style scoped>
.ant-form-item {
    margin-bottom: 4px;
    margin-left: 4px;
}
.ant-input-affix-wrapper {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    color: rgba(0, 0, 0, 0.65);
    font-size: 14px;
    font-variant: tabular-nums;
    line-height: 1.5;
    list-style: none;
    font-feature-settings: 'tnum';
    position: relative;
    display: inline-block;
    width: 107%;
    text-align: start;
}
</style>
